package com.example.forum.controller;

import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author YJ
 * @Date 2023/8/16 10:01
 * Description:UserController实现
 */

@Api(tags = "用户接口")
//路由映射
@RestController
@RequestMapping("/user")
//日志注解
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 用户注册
     *
     * @param username       用户名
     * @param nickname       用户昵称
     * @param password       用户密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam(value = "用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam(value = "昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam(value = "密码") @RequestParam("password") @NonNull String password,
                              @ApiParam(value = "重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        /*if(StringUtil.isEmpty(username)||StringUtil.isEmpty(nickname)
        ||StringUtil.isEmpty(password)||StringUtil.isEmpty(passwordRepeat)) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/
        //校验两次密码是否一致
        if (!password.equals(passwordRepeat)) {
            //打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐
        String salt = UUIDUtil.UUID_32();
        //生成密文
        String ciphertext = MD5Util.md5Salt(password, salt);
        //设置密码
        user.setPassword(ciphertext);
        //设置盐
        user.setSalt(salt);
        //调用Service层方法
        userService.createNormalUser(user);
        //返回成功
        return AppResult.success();
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam(value = "用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam(value = "密码") @RequestParam("password") @NonNull String password) {
        //1.调用service层的方法
        User user = userService.Login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2.把返回的user对象添加到Session中
        //getSession(true)表示没有Session对象时创建一个Session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        //3.返回结果
        return AppResult.success();
    }

    /**
     * 获取用户信息
     *
     * @param request 获取session对象
     * @param id      用户id(非必传参数)
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam(value = "用户id") @RequestParam(value = "id", required = false) Long id) {
        //定义返回的uer对象
        User user = null;
        //1.id为空，从session中获取当前用户信息
        if (id == null) {
            //获取session
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            //2.id不为空，从数据库按id查询用户信息
            user = userService.selectById(id);
        }
        //判断用户对象是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //返回正常结果
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //获取session对象
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if (session != null) {
            log.info("退出成功");
            //表示用户在登录状态,销毁session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     *
     * @param username 用户名
     * @param nickname 用户昵称
     * @param gender   用户性别
     * @param email    用户邮箱
     * @param phoneNum 用户电话
     * @param remark   个人简介
     * @return
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam(value = "用户名") @RequestParam(value = "username", required = false) String username,
                                @ApiParam(value = "用户昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @ApiParam(value = "用户性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @ApiParam(value = "用户邮箱") @RequestParam(value = "email", required = false) String email,
                                @ApiParam(value = "用户电话") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @ApiParam(value = "个人简介") @RequestParam(value = "remark", required = false) String remark) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //非空检验
        if (StringUtil.isEmpty(username)
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark)
                && gender == null) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        User updateUser = new User();
        //从session中获取id
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //调用service中的方法
        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        user = userService.selectById(user.getId());
        //把最新用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        //返回结果
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPassword")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam(value = "旧密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam(value = "新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam(value = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验新密码与确认密码是否相同
        if (!newPassword.equalsIgnoreCase(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //调用service方法
        userService.modifyPassword(user.getId(), oldPassword, newPassword);
        //销毁session
        /*if (session != null) {
            session.invalidate();
        }*/
        //返回结果
        return AppResult.success();
    }
}
